package cn.jx.asc.socket;

/*
 * 负责与终端进行通信
 *
 */

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

import org.json.*;

public class CommunicationWithTerminal extends Thread {
    InputStreamReader in = null;
    OutputStreamWriter out = null;
    Socket socket = null;
    int id = -1;
    Scanner sc = null;
    char data[] = new char[1024];	// 存储数据的字节数组

    public CommunicationWithTerminal(Socket s) {
        this.socket = s;

        try {
            in = new InputStreamReader(socket.getInputStream()); // 获取socket的输出流与输入流
            out = new OutputStreamWriter(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("***get socket stream error***");
        }
    }

    public void run() {
        while(true) {
            sc = new Scanner(in);		//获取输入
            String line = sc.nextLine();
            JSONObject jsonData = null;

            try {
                jsonData = new JSONObject(line);	//将输入转换为json
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            try {
                id = jsonData.getInt("ID");			//获取终端id
                System.out.println("---终端id---"+id);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println("***data analysis error***");
            }

            //通过handleData类的handle方法对传输的数据进行处理
            //并获取处理结果，若处理成功为true，失败为false
            try {
                if(new HandleData(id,jsonData).handle()) {
                    //System.out.println("***data handle success***");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            if(InstructAndResult.hasInstructs(id)) {	//查找是否有需要发送到该终端的指令
                if(new SendInstruct(id,in,out).send()) {
                    System.out.println("***instructsss send success***");
                }else {
                    System.out.println("***instructsss send fail***");
                }
            }
        }

    }
}
